<template>
  <Card
    v-loading="loading"
    title="编辑消息"
    :bordered="false"
    :head-style="{ padding: '0' }"
    :body-style="{ padding: '10px 0' }"
  >
    <div style="background-color: #e7eff6" class="flex justify-start gap-2 p-8px mb-2">
      <Button type="primary" @click="handleReturn">
        <template #icon>
          <RollbackOutlined />
        </template>
        返回
      </Button>
      <Button type="primary" @click="handleRefresh">
        <template #icon>
          <RedoOutlined />
        </template>
        刷新
      </Button>
    </div>
    <BasicForm @register="registerForm">
      <template #userRealName="{ model, field }">
        <FormItemRest>
          <SelectUserInput
            :hadUsers="dataRef['hadUsers']"
            v-model:value="model[field]"
            @change="(val, node) => handleUserRealName(val, node, field)"
          />
        </FormItemRest>
      </template>
      <template #csms>
        <div>
          <a-button type="link" @click="handleCS">{{ iscs ? '删除抄送' : '添加抄送' }}</a-button>
          <!-- <a-button type="link" @click="handleMS">{{ isms ? '删除密送' : '添加密送' }}</a-button> -->
        </div>
      </template>
      <template #userRealName1="{ model, field }">
        <SelectUserInput
          :hadUsers="dataRef['hadUsers1']"
          v-model:value="model[field]"
          @change="(val, node) => handleUserRealName1(val, node, field)"
        />
      </template>
      <template #userRealName2="{ model, field }">
        <SelectUserInput
          :hadUsers="dataRef['hadUsers2']"
          v-model:value="model[field]"
          @change="(val, node) => handleUserRealName2(val, node, field)"
        />
      </template>
      <template #send_now="{ model, field }">
        <FormItemRest>
          <div style="text-align: left">
            <RadioGroup v-model:value="model[field]">
              <Radio :style="radioStyle" value="yes">立即发送</Radio>
              <Radio :style="radioStyle" value="no">
                定时发送
                <DatePicker
                  class="ml-2"
                  v-model:value="dataRef.send_time"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                  :show-time="true"
                />
              </Radio>
            </RadioGroup>
          </div>
        </FormItemRest>
      </template>
      <template #att>
        <FormItemRest>
          <div class="text-left">
            <Upload
              :file-list="fileList"
              :before-upload="beforeUpload"
              @remove="handleRemove"
              multiple
            >
              <a-button>
                <upload-outlined />
                上传文件
              </a-button>
            </Upload>
          </div>
        </FormItemRest>
      </template>
      <template #att2>
        <FormItemRest>
          <div>
            <div v-for="(item, index) in dataRef.attachments" :key="item.id">
              <a @click="handleClickFile(item)">{{ item.name }}</a>
              <DeleteOutlined
                class="ml-2"
                style="color: red"
                @click="handleDeleteFile(item, index)"
              />
            </div>
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
    <div class="flex justify-center gap-2">
      <a-button type="primary" @click="handleSave" v-if="type == 'draftbox'">保存</a-button>
      <a-button type="primary" @click="handleSend" v-if="type == 'draftbox'">发送</a-button>
      <Popconfirm
        placement="top"
        title="确定重新发送吗？"
        ok-text="确定"
        cancel-text="取消"
        v-if="type == 'outBox'"
        @confirm="handleResetSend"
      >
        <a-button type="primary">重新发送</a-button></Popconfirm
      >
      <a-button type="primary" @click="handleWithdraw" v-if="type == 'outBox'">撤回</a-button>
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, nextTick, onMounted, h, inject } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, radioStyle } from './writeboxForm.data';
  import {
    Form,
    Radio,
    RadioGroup,
    DatePicker,
    Card,
    Upload,
    UploadProps,
    Button,
    Popconfirm,
  } from 'ant-design-vue';
  import {
    UploadOutlined,
    RedoOutlined,
    RollbackOutlined,
    DeleteOutlined,
  } from '@ant-design/icons-vue';
  import { SelectUserInput } from '/@/components/CustomComp';
  import {
    getMessage_oaEditDraftPage,
    getMessage_oaUpdateDraft,
    getMessage_oaTransmit,
    getMessage_oaRecall,
    getMessage_oaDelAttachment,
  } from '/@/api/email/email';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isArray } from '/@/utils/is';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();
  const serverInfo = userStore.getServerInfo;

  const props = defineProps({
    type: {
      type: String,
      default: 'draftbox',
    },
    currentRecord: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  const { createMessage, createConfirm } = useMessage();
  const emit = defineEmits(['handle-return']);
  const internalEmail = inject('internalEmail') as any;
  const current = ref(0);
  const FormItemRest = Form.ItemRest;
  const iscs = ref(false);
  const isms = ref(false);
  const ishj = ref(false);
  const loading = ref(false);
  const dataRef = ref<Recordable>({
    send_now: 'yes',
    send_time: '',
    receiver: '',
    isToOutBox: 'true',
    receipt_state: 0,
    msg_level: 0,
  });

  const [registerForm, { resetFields, validate, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const init = () => {
    nextTick(async () => {
      if (props.type == 'outBox') {
        ishj.value = false;
      } else {
        ishj.value = true;
      }
      setFields();
      resetFields();

      if (!props.currentRecord.id) return;
      loading.value = true;
      const res = await getMessage_oaEditDraftPage({ id: props.currentRecord.id });
      dataRef.value = {
        ...res,
        receipt_state: res.receiptState,
        msg_level: res.msgLevel,
        send_now: res.isSent == 1 ? 'yes' : 'no',
        isToOutBox: res.isToOutBox ? 'true' : 'false',
        userRealName: res.realNameJs,
        userRealName1: res.realNameCs,
        userRealName2: res.realNameMs,
        receiver: res.receiversjs,
        receiver1: res.receiverscs,
        receiver2: res.receiversms,
        send_time: res.sendTime,
        deptCodes: res.deptCodes ? res.deptCodes.split(',') : [],
      };
      loading.value = false;
      dataRef.value.hadUsers = [];
      dataRef.value.hadUsers1 = [];
      dataRef.value.hadUsers2 = [];
      if (dataRef.value.receiver) {
        const receivers = dataRef.value.receiver.split(',');
        const userRealNames = dataRef.value.userRealName.split(',');
        if (dataRef.value.receiver.indexOf('dept@') != -1) {
          dataRef.value.deptCodes = receivers.map((item) => item.replaceAll('dept@', ''));
          dataRef.value.receiver = '';
          current.value = 1;
          updateSchema([
            {
              field: 'deptCodes',
              ifShow: true,
            },
          ]);
          updateSchema([
            {
              field: 'userRealName',
              ifShow: false,
            },
          ]);
        } else {
          userRealNames.forEach((item, index) => {
            dataRef.value.hadUsers.push({
              key: receivers[index],
              name: receivers[index],
              title: item,
              realName: item,
            });
          });
        }
      }
      if (dataRef.value.receiver1) {
        iscs.value = true;
        const receivers1 = dataRef.value.receiver1.split(',');
        const userRealNames1 = dataRef.value.userRealName1.split(',');
        userRealNames1.forEach((item, index) => {
          dataRef.value.hadUsers1.push({
            key: receivers1[index],
            name: receivers1[index],
            title: item,
            realName: item,
          });
        });
      } else {
        iscs.value = false;
      }
      // if (dataRef.value.receiver2) {
      //   isms.value = true;
      //   const receivers2 = dataRef.value.receiver2.split(',');
      //   const userRealNames2 = dataRef.value.userRealName2.split(',');
      //   userRealNames2.forEach((item, index) => {
      //     dataRef.value.hadUsers2.push({
      //       key: receivers2[index],
      //       name: receivers2[index],
      //       title: item,
      //       realName: item,
      //     });
      //   });
      // } else {
      //   isms.value = false;
      // }
      setCS();
      setMS();
      setFieldsValue({ ...dataRef.value });
    });
  };

  onMounted(init);

  const fileList = ref<UploadProps['fileList']>([]);
  const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  };
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    fileList.value = [...fileList.value, file];
    return false;
  };

  const handleReturn = () => {
    emit('handle-return');
  };
  const handleRefresh = () => {
    init();
  };
  const handleCS = () => {
    iscs.value = !iscs.value;
    setCS();
  };
  const setCS = () => {
    if (iscs.value) {
      updateSchema([
        {
          field: 'userRealName1',
          ifShow: true,
        },
      ]);
    } else {
      updateSchema([
        {
          field: 'userRealName1',
          ifShow: false,
        },
      ]);
    }
  };
  const handleMS = () => {
    isms.value = !isms.value;
    setMS();
  };
  const setMS = () => {
    // if (isms.value) {
    //   updateSchema([
    //     {
    //       field: 'userRealName2',
    //       ifShow: true,
    //     },
    //   ]);
    // } else {
    //   updateSchema([
    //     {
    //       field: 'userRealName2',
    //       ifShow: false,
    //     },
    //   ]);
    // }
  };

  const handleUserRealName = (val, node, field) => {
    console.log('node', val, node);
    const { dataRef: _dataRef, selectUsers } = node;
    dataRef.value.receiver = _dataRef.userNames;
    dataRef.value[field] = val;
    dataRef.value.hadUsers = selectUsers;
    setFieldsValue({ [field]: val });
  };
  const handleUserRealName1 = (val, node, field) => {
    console.log('node', val, node);
    const { dataRef: _dataRef, selectUsers } = node;
    dataRef.value.receiver1 = _dataRef.userNames;
    dataRef.value[field] = val;
    dataRef.value.hadUsers1 = selectUsers;
    setFieldsValue({ [field]: val });
  };
  const handleUserRealName2 = (val, node, field) => {
    console.log('node', val, node);
    const { dataRef: _dataRef, selectUsers } = node;
    dataRef.value.receiver2 = _dataRef.userNames;
    dataRef.value[field] = val;
    dataRef.value.hadUsers2 = selectUsers;
    setFieldsValue({ [field]: val });
  };

  const handleSave = async () => {
    try {
      const values = await validate();
      console.log('values', values);
      const data = Object.assign({}, dataRef.value, values);
      // Reflect.deleteProperty(data, 'hadUsers');
      // Reflect.deleteProperty(data, 'hadUsers1');
      // Reflect.deleteProperty(data, 'hadUsers2');
      // Reflect.deleteProperty(data, 'attachments');
      // Reflect.deleteProperty(data, 'primaryKey');
      if (internalEmail.emailType.value == 2 && current.value == 1) {
        if (isArray(data.deptCodes) && data.deptCodes.length) {
          data.receiver = data.deptCodes.map((item) => `dept@${item}`).join(',');
        } else {
          data.receiver = '';
        }
      }
      Reflect.deleteProperty(data, 'deptCodes');
      fileList.value?.forEach((item, index) => {
        data[`att${index + 1}`] = item;
      });
      const formata = new FormData();
      for (let v in data) {
        formata.append(v, data[v]);
      }
      console.log('data', data);
      loading.value = true;
      await getMessage_oaUpdateDraft(formata);
    } catch (error) {
      console.log('handleSave', error);
    } finally {
      loading.value = false;
    }
  };
  const handleSend = async () => {
    try {
      const values = await validate();
      console.log('values', values);
      console.log('dataRef.value', dataRef.value);
      const data = Object.assign({}, dataRef.value, values);
      Reflect.deleteProperty(data, 'hadUsers');
      Reflect.deleteProperty(data, 'hadUsers1');
      Reflect.deleteProperty(data, 'hadUsers2');
      Reflect.deleteProperty(data, 'attachments');
      Reflect.deleteProperty(data, 'primaryKey');
      if (internalEmail.emailType.value == 2 && current.value == 1) {
        if (isArray(data.deptCodes) && data.deptCodes.length) {
          data.receiver = data.deptCodes.map((item) => `dept@${item}`).join(',');
        } else {
          data.receiver = '';
        }
      }
      Reflect.deleteProperty(data, 'deptCodes');
      fileList.value?.forEach((item, index) => {
        data[`att${index + 1}`] = item;
      });
      const formata = new FormData();
      for (let v in data) {
        formata.append(v, data[v]);
      }
      console.log('data', data);
      loading.value = true;
      await getMessage_oaTransmit(formata, data.id);
      createMessage.success('操作成功');
      handleReturn();
    } catch (error) {
      console.log('handleSave', error);
    } finally {
      loading.value = false;
    }
  };
  //重新发送
  const handleResetSend = () => {
    dataRef.value.isToOutBox = true;
    handleSend();
  };
  //撤回
  const handleWithdraw = async () => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '您确定撤回么？'),
      onOk: async () => {
        try {
          await getMessage_oaRecall({ id: props.currentRecord.id });
          handleReturn();
        } catch (error) {
          console.log(error);
        }
      },
    });
  };

  const setFields = () => {
    updateSchema([
      {
        field: 'att',
        ifShow: true,
      },
    ]);
    updateSchema([
      {
        field: 'att2',
        ifShow: true,
      },
    ]);

    if (ishj.value) {
      updateSchema([
        {
          field: 'send_now',
          ifShow: true,
        },
      ]);
      // updateSchema([
      //   {
      //     field: 'isToOutBox',
      //     ifShow: true,
      //   },
      // ]);
      updateSchema([
        {
          field: 'receipt_state',
          ifShow: true,
        },
      ]);
      updateSchema([
        {
          field: 'msg_level',
          ifShow: true,
        },
      ]);
    } else {
      updateSchema([
        {
          field: 'send_now',
          ifShow: false,
        },
      ]);
      // updateSchema([
      //   {
      //     field: 'isToOutBox',
      //     ifShow: false,
      //   },
      // ]);
      updateSchema([
        {
          field: 'receipt_state',
          ifShow: false,
        },
      ]);
      updateSchema([
        {
          field: 'msg_level',
          ifShow: false,
        },
      ]);
    }
  };
  //点击附件
  const handleClickFile = (record) => {
    const path = record.visualPath + '/' + record.diskName;
    const fileName = record.name;
    const url = path
      ? serverInfo.rootPath + (path && path.startsWith('/') ? path : `/${path}`)
      : '';
    downloadByUrl({ url, fileName });
  };

  //删除附件
  const handleDeleteFile = async (item, index) => {
    try {
      console.log('item,index', item, index);
      createConfirm({
        iconType: 'warning',
        title: () => h('span', '您确定删除么？'),
        onOk: async () => {
          try {
            await getMessage_oaDelAttachment({
              attId: item.id,
              msgId: props.currentRecord.id,
            });
            dataRef.value.attachments.splice(index, 1);
            // const res = await getMessage_oaEditDraftPage({ id: props.currentRecord.id });
            // dataRef.value.attachments = res.attachments || [];
          } catch (error) {
            console.log(error);
          }
        },
      });
    } catch (error) {
      console.error('handleDeleteFile', error);
    }
  };
</script>

<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
</style>
